package org.hypnus.e.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.hypnus.e.exception.EException;

public abstract class DateUtil {

	public static final DateFormat dateFmt = new SimpleDateFormat(EConstants.DATE_FORMAT);

	public static final DateFormat datetimeFmt = new SimpleDateFormat(EConstants.DATETIME_FORMAT);

	public static String toString(Date date, String format) {
		if (date == null || format == null) {
			throw new IllegalArgumentException("\u53C2\u6570\u4E0D\u5408\u6CD5");
		}
		String strDate = null;
		if (StringUtils.equals(EConstants.DATE_FORMAT, format)) {
			strDate = dateFmt.format(date);
		} else if (StringUtils.equals(EConstants.DATETIME_FORMAT, format)) {
			strDate = datetimeFmt.format(date);
		} else {
			DateFormat tmp = new SimpleDateFormat(format);
			strDate = tmp.format(date);
		}
		return strDate;
	}

	public static Date toDate(String value, String format) {
		if (value == null || format == null) {
			throw new IllegalArgumentException("\u53C2\u6570\u4E0D\u5408\u6CD5");
		}
		Date date = null;
		try {
			if (StringUtils.equals(EConstants.DATE_FORMAT, format)) {
				date = dateFmt.parse(value);
			} else if (StringUtils.equals(EConstants.DATETIME_FORMAT, format)) {
				date = datetimeFmt.parse(value);
			} else {
				DateFormat tmp = new SimpleDateFormat(format);
				date = tmp.parse(value);
			}
		} catch (ParseException e) {
			throw new EException(e.getMessage(), e) ;
		}
		return date;
	}

	public static void main(String[] args) throws ParseException {
//		System.out.println(DateFormat.getInstance().parse("2013-05-11").toString());
		DateFormat tmp = new SimpleDateFormat("yyyy-MM-dd");
		Date date = tmp.parse("2013-05-11 11:54:44");
		System.out.println(date.toString());
	}
}
